package Team.Yaohuo.utils;


import Team.Yaohuo.properties.WxProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.*;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.*;

import static org.jacoco.agent.rt.internal_035b120.core.runtime.AgentOptions.OutputMode.file;

@Component
public class WxUtil {

    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private WxProperties wxProperties;

    /**
     * 根据用户id获取用户名称
     *
     * @param userId
     * @param access_token
     * @return
     */
    public String getUserDetail(String userId, String access_token) {
        String url = "https://qyapi.weixin.qq.com/cgi-bin/user/get?access_token=" + access_token + "&userid=" + userId;
        ResponseEntity<Map> exchange = restTemplate.exchange(url, HttpMethod.GET, null, Map.class);
        String name = (String) exchange.getBody().get("name");
        return name;
    }

    /**
     * 获取media_id
     */
    public String fileUpload(String access_token, String type) throws URISyntaxException, FileNotFoundException {
        String url = "https://qyapi.weixin.qq.com/cgi-bin/media/upload?access_token=" + access_token + "&type=" + type;

        // 设置请求头，指定内容类型为 multipart/form-data，用于文件上传
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.MULTIPART_FORM_DATA);
        // 获取当前类的类加载器
        ClassLoader classLoader = WxUtil.class.getClassLoader();
        // 通过类加载器获取资源对应的URL，这里传入资源文件的相对路径（相对于类路径下的resources目录）
        URL resourceUrl = classLoader.getResource("static/yaohuorj.png");
        // 将URL转换为Path对象，以便后续操作
        Path path = Paths.get(Objects.requireNonNull(resourceUrl).toURI());
        // 尝试获取文件对象
        File file = path.toFile();
        // 创建用于存放文件及参数的MultiValueMap
        MultiValueMap<String, Object> body = new LinkedMultiValueMap<>();
        if (!file.exists()) {
            return "文件不存在，请检查文件路径";
        }
        // 将文件添加到请求体中，使用 FileSystemResource 来封装文件
        body.add("media", new org.springframework.core.io.FileSystemResource(file));
        // 封装请求头和请求体为HttpEntity
        HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(body, headers);
        // 使用RestTemplate发送POST请求进行文件上传，并获取响应
        ResponseEntity<Map> response = restTemplate.exchange(url, HttpMethod.POST, requestEntity, Map.class);
        return response.getBody().get("media_id").toString();
    }

    /**
     * 消息推送 方案一 文本类型
     * @param userId
     * @param access_token
     * @param date
     * @param ipAddr
     * @param address
     * @return
     */
    public Map<String, Object> messagePushTextType(String userId,String access_token, String date, String ipAddr, String address ) {
        Map<String, Object> meg = new HashMap<>();
        meg.put("touser", userId);
        meg.put("msgtype", "textcard");
        meg.put("agentid", wxProperties.getAgentid());
        meg.put("textcard", new HashMap<>(){{
            put("title", "登录通知");
            put("description", "<div class=\"gray\">"+date+"</div> <div class=\"normal\">当前访问ip地址："+ipAddr+"</div><div class=\"highlight\">"+address+"</div>");
            put("url", "https://www.jiandaoyun.com/dashboard");
            put("btntxt", "详细");
        }});
        meg.put("enable_id_trans", 0);
        meg.put("enable_duplicate_check", 0);
        meg.put("duplicate_check_interval", 0);
        return meg;
    }

    /**
     * 消息推送 方案二 图片类型
     * @param userId
     * @param access_token
     * @param date
     * @param ipAddr
     * @param address
     * @return
     */
    public Map<String, Object> messagePushImageType(String userId,String access_token, String date, String ipAddr, String address) throws FileNotFoundException, URISyntaxException {
        Map<String, Object> meg = new HashMap<>();
        List<Object> articlesList = new ArrayList<>();
        Map<String, Object> articlesMap = new HashMap<>();
        articlesMap.put("title", "登录通知");
        // 获取media_id
        String mediaId = fileUpload(access_token, "image");
        articlesMap.put("thumb_media_id", mediaId);
        articlesMap.put("author", "liuxintong");
        articlesMap.put("content_source_url", "https://open.weixin.qq.com/connect/oauth2/authorize?appid=ww9cbdb9ca4b0d4236&redirect_uri=http%3A%2F%2Fwww.yaohuo.team%2FgetWxAuto&state=yaohuokeji&response_type=code&scope=snsapi_base&agentid=1000014#wechat_redirect");
        articlesMap.put("content", "简道云");
        articlesMap.put("digest", "点击查看登录详情");
        articlesList.add(articlesMap);
        meg.put("touser", userId);
        meg.put("msgtype", "mpnews");
        meg.put("agentid", wxProperties.getAgentid());
        meg.put("mpnews", new HashMap<>() {{
            put("articles", articlesList);
        }});
        meg.put("enable_id_trans", 0);
        meg.put("enable_duplicate_check", 0);
        meg.put("duplicate_check_interval", 0);
        return meg;
    }

    /**
     * 消息推送 方案三 模板图文类型
     * @param userId
     * @param access_token
     * @param date
     * @param ipAddr
     * @param address
     * @return
     */
    public Map<String, Object> messagePushTemplateImageTextType(String userId,String access_token, String date, String ipAddr, String address) {
        Map<String, Object> meg = new HashMap<>();
        meg.put("touser", userId);
        meg.put("msgtype", "template_card");
        meg.put("agentid", wxProperties.getAgentid());
        Map<String, Object> templateCard = new HashMap<>();
        templateCard.put("card_type", "news_notice");
        // 构建 source 对应的Map
        Map<String, Object> source = new HashMap<>();
        source.put("icon_url", "https://yaohuojdy.oss-cn-shanghai.aliyuncs.com/%E6%91%87%E7%81%AB%E8%BD%AF%E4%BB%B6%E7%A7%91%E6%8A%801.png");
        source.put("desc", "企业微信");
        source.put("desc_color", 1);
        templateCard.put("source", source);

        // 构建 main_title 对应的Map
        Map<String, Object> mainTitle = new HashMap<>();
        mainTitle.put("title", "欢迎使用摇火简道云");
        mainTitle.put("desc", "您的好友正在邀请您加入简道云");
        templateCard.put("main_title", mainTitle);

        // 构建 image_text_area 对应的Map
        Map<String, Object> imageTextArea = new HashMap<>();
        imageTextArea.put("type", 1);
        imageTextArea.put("url", "https://open.weixin.qq.com/connect/oauth2/authorize?appid=ww9cbdb9ca4b0d4236&redirect_uri=http%3A%2F%2Fwww.yaohuo.team%2FgetWxAuto&state=yaohuokeji&response_type=code&scope=snsapi_base&agentid=1000014#wechat_redirect");
        imageTextArea.put("image_url", "https://yaohuojdy.oss-cn-shanghai.aliyuncs.com/%E6%91%87%E7%81%AB%E8%BD%AF%E4%BB%B6%E7%A7%91%E6%8A%801.png");
        templateCard.put("image_text_area", imageTextArea);

        // 构建 card_image 对应的Map
        Map<String, Object> cardImage = new HashMap<>();
        cardImage.put("url", "https://yaohuojdy.oss-cn-shanghai.aliyuncs.com/%E6%91%87%E7%81%AB%E8%BD%AF%E4%BB%B6%E7%A7%91%E6%8A%801.png");
        cardImage.put("aspect_ratio", 1.3);
        templateCard.put("card_image", cardImage);

        // 构建 vertical_content_list 对应的List，里面包含Map元素
        List<Map<String, Object>> verticalContentList = new ArrayList<>();
        Map<String, Object> verticalContent = new HashMap<>();
        verticalContent.put("title", "当前访问ip:" + ipAddr);
        verticalContent.put("desc", "位置:"+ address);
        verticalContentList.add(verticalContent);
        templateCard.put("vertical_content_list", verticalContentList);

        // 构建 horizontal_content_list 对应的List，里面包含Map元素
        List<Map<String, Object>> horizontalContentList = new ArrayList<>();

        Map<String, Object> horizontalContent1 = new HashMap<>();
        horizontalContent1.put("keyname", "当前用户");
        horizontalContent1.put("value", this.getUserDetail(userId, access_token));
        horizontalContentList.add(horizontalContent1);

        Map<String, Object> horizontalContent2 = new HashMap<>();
        horizontalContent2.put("type", 1);
        horizontalContent2.put("keyname", "简道云官网");
        horizontalContent2.put("value", "点击访问");
        horizontalContent2.put("url", "https://www.jiandaoyun.com");
        horizontalContentList.add(horizontalContent2);

        Map<String, Object> horizontalContent4 = new HashMap<>();
        horizontalContent4.put("type", 3);
        horizontalContent4.put("keyname", "员工信息");
        horizontalContent4.put("value", "点击查看");
        horizontalContent4.put("userid", userId);
        horizontalContentList.add(horizontalContent4);
        templateCard.put("horizontal_content_list", horizontalContentList);

        // 构建 card_action 点击卡牌跳转公司简道云
        Map<String, Object> cardAction = new HashMap<>();
        cardAction.put("type", 1);
        cardAction.put("url", "https://open.weixin.qq.com/connect/oauth2/authorize?appid=ww9cbdb9ca4b0d4236&redirect_uri=http%3A%2F%2Fwww.yaohuo.team%2FgetWxAuto&state=yaohuokeji&response_type=code&scope=snsapi_base&agentid=1000014#wechat_redirect");
        templateCard.put("card_action", cardAction);
        meg.put("template_card", templateCard);
        // 设置 enable_id_trans
        meg.put("enable_id_trans", 0);
        // 设置 enable_duplicate_check
        meg.put("enable_duplicate_check", 0);
        // 设置 duplicate_check_interval
        meg.put("duplicate_check_interval", 1800);

        return meg;
    }

    /**
     * 简道云消息待办
     * @param userId
     * @param waitMapJdy
     * @return
     */
    public Map<String, Object> messagePushTextTypeWaitJDY(String userId, Map waitMapJdy, String count) {

        String formTitle = (String) waitMapJdy.get("form_title");
        String url = (String) waitMapJdy.get("url");

        Map<String, Object> meg = new HashMap<>();
        meg.put("touser", userId);
        meg.put("msgtype", "textcard");
        meg.put("agentid", wxProperties.getAgentid());

        if (count.equals("0")) {
            meg.put("textcard", new HashMap<>(){{
                put("title", "简道云待办通知");
                put("description", "<div class=\"highlight\">"+ "当前共计"+ count + "条代办</div><div class=\"normal\">代办名称："+formTitle+"</div>");
                put("url", "https://www.jiandaoyun.com/dashboard#/flow/internal/todo");
                put("btntxt", "详细");
            }});
        }else {
            meg.put("textcard", new HashMap<>(){{
                put("title", "简道云待办通知");
                put("description", "<div class=\"highlight\">"+ "当前共计"+ count + "条代办</div><div class=\"normal\">代办名称："+formTitle+"......</div>");
                put("url", "https://www.jiandaoyun.com/dashboard#/flow/internal/todo");
                put("btntxt", "详细");
            }});
        }

        meg.put("enable_id_trans", 0);
        meg.put("enable_duplicate_check", 0);
        meg.put("duplicate_check_interval", 0);
        return meg;
    }
}
